package com.taskmanager.controller;

import com.taskmanager.dto.TaskListResponse;
import com.taskmanager.dto.TaskRequest;
import com.taskmanager.dto.TaskResponse;
import com.taskmanager.service.TaskService;
import com.taskmanager.util.ApiResponse;
import com.taskmanager.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务控制器
 * 处理任务的增删改查、筛选、排序等请求
 */
@RestController
@RequestMapping("/api/task")
public class TaskController {
    
    @Autowired
    private TaskService taskService;
    
    /**
     * 创建任务
     * POST /api/task
     */
    @PostMapping
    public ApiResponse<TaskResponse> createTask(
            @Validated @RequestBody TaskRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = (Long) httpRequest.getAttribute("userId");
            TaskResponse response = taskService.createTask(userId, request);
            return ResponseUtil.success("创建成功", response);
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("创建任务失败");
        }
    }
    
    /**
     * 查询任务列表（支持筛选和排序）
     * GET /api/task/list
     * 参数：keyword, status, priority, categoryId, sortBy, sortOrder
     */
    @GetMapping("/list")
    public ApiResponse<TaskListResponse> getTaskList(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String priority,
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false, defaultValue = "createdAt") String sortBy,
            @RequestParam(required = false, defaultValue = "DESC") String sortOrder,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            TaskListResponse response = taskService.getTaskList(
                userId, keyword, status, priority, categoryId, sortBy, sortOrder
            );
            return ResponseUtil.success(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("查询任务列表失败");
        }
    }
    
    /**
     * 查询任务详情
     * GET /api/task/{taskId}
     */
    @GetMapping("/{taskId}")
    public ApiResponse<TaskResponse> getTaskById(
            @PathVariable Long taskId,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            TaskResponse response = taskService.getTaskById(taskId, userId);
            return ResponseUtil.success(response);
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("查询任务详情失败");
        }
    }
    
    /**
     * 更新任务
     * PUT /api/task/{taskId}
     */
    @PutMapping("/{taskId}")
    public ApiResponse<TaskResponse> updateTask(
            @PathVariable Long taskId,
            @Validated @RequestBody TaskRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = (Long) httpRequest.getAttribute("userId");
            TaskResponse response = taskService.updateTask(taskId, userId, request);
            return ResponseUtil.success("更新成功", response);
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("更新任务失败");
        }
    }
    
    /**
     * 删除任务
     * DELETE /api/task/{taskId}
     */
    @DeleteMapping("/{taskId}")
    public ApiResponse<Void> deleteTask(
            @PathVariable Long taskId,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            taskService.deleteTask(taskId, userId);
            return ResponseUtil.success("删除成功");
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("删除任务失败");
        }
    }
    
    /**
     * 更新任务状态
     * PATCH /api/task/{taskId}/status
     */
    @PatchMapping("/{taskId}/status")
    public ApiResponse<TaskResponse> updateTaskStatus(
            @PathVariable Long taskId,
            @RequestBody Map<String, String> body,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            String status = body.get("status");
            
            if (status == null || status.isEmpty()) {
                return ResponseUtil.error("状态不能为空");
            }
            
            TaskResponse response = taskService.updateTaskStatus(taskId, userId, status);
            return ResponseUtil.success("状态更新成功", response);
        } catch (IllegalArgumentException e) {
            return ResponseUtil.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("更新状态失败");
        }
    }
    
    /**
     * 查询即将到期的任务
     * GET /api/task/upcoming
     */
    @GetMapping("/upcoming")
    public ApiResponse<List<TaskResponse>> getUpcomingTasks(
            @RequestParam(required = false, defaultValue = "3") int days,
            HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            List<TaskResponse> tasks = taskService.getUpcomingTasks(userId, days);
            return ResponseUtil.success(tasks);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("查询即将到期任务失败");
        }
    }
    
    /**
     * 获取任务统计信息
     * GET /api/task/statistics
     */
    @GetMapping("/statistics")
    public ApiResponse<Map<String, Integer>> getStatistics(HttpServletRequest request) {
        try {
            Long userId = (Long) request.getAttribute("userId");
            Map<String, Integer> statistics = taskService.getTaskStatistics(userId);
            return ResponseUtil.success(statistics);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("获取统计信息失败");
        }
    }
}
